package net.cellkyborg.server;

public class LoginServer implements Runnable {
	
	int loginPort = 43594;
	java.net.ServerSocket listenSocket = null;
	
	boolean shutdown = false;
	int restartRetry = 0;
	
	public LoginServer() {
		
	}
	
	public void run() {
		while (!shutdown) {
			if (listenSocket==null) {
				try {
					listenSocket = new java.net.ServerSocket(loginPort, 1, null);
					restartRetry = 0;
				}
				catch (java.io.IOException ioexception) {
					restartRetry++;
					listenSocket = null;
				}
				if (restartRetry>10) {
					break;
				}
			}
			if (listenSocket!=null) {
				try {
					java.net.Socket s = listenSocket.accept();
					s.setTcpNoDelay(true);
					
					String ip = s.getInetAddress().getHostName();
					
					if (canConnect(ip)) {
						int connType = s.getInputStream().read();
						if (connType == 14) {
							server.playerHandler.newPlayerClient(s);							
						} else if (connType == 15) {
							(new Thread(new UpdateServer(s))).start();
						} else {
							s.close();
						}
					}
					else {
						s.close();
					}
					
				}
				catch (java.io.IOException ioexception) { }
			}
		}
		try {
			listenSocket.close();
		}
		catch (Exception ex) {}
	}
	
	boolean canConnect(String s) {
		return true;
	}
	
	public void shutdown() {
		shutdown = true;
	}
}